<?php

namespace frontend\modules\screen\controllers;

use common\components\Category;
use common\components\Upload;
use common\models\articlesite\ArticlesiteArticle;
use common\models\articlesite\ArticlesiteCategory;
use common\models\business\BusinessAdress;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessInspection;
use common\models\business\BusinessPig;
use common\models\business\BusinessPigFile;
use common\models\business\BusinessUser;
use common\models\business\BusinessVariety;
use common\models\business\NewBusinessInspection;
use common\models\business\NewBusinessInspectionData;
use common\models\sys\SysSetting;
use common\models\wechat\WechatFans;
use dosamigos\qrcode\QrCode;
use EasyWeChat\Message\Article;
use frontend\controllers\BaseController;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;

/**
 * Default controller for the `screen` module
 */
class SiteController extends BaseController
{
    public $layout = false;
    public $enableCsrfValidation = false;
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {

        $count = BusinessFarmers::find()->count();
        $pig = BusinessPig::find()->where('status<:status',[':status'=>BusinessPig::STATUS_KILLED])->count();
        $fansconut = BusinessUser::find()->count();

        $bg = Upload::checkGetUrl(SysSetting::getValue('screen_bgimg1'));

        return $this->render('@template/screen/index.html',['count'=>$count,'pigcount'=>$pig,'fanscount'=>$fansconut,'bg'=>$bg]);
    }

    public function actionIndex2()
    {
        $count = BusinessFarmers::find()->count();
        $pig = BusinessPig::find()->where('status<:status',[':status'=>BusinessPig::STATUS_KILLED])->count();
        $fansconut = BusinessUser::find()->count();

        $bg = Upload::checkGetUrl(SysSetting::getValue('screen_bgimg2'));

        return $this->render('@template/screen/index2.html',['count'=>$count,'pigcount'=>$pig,'fanscount'=>$fansconut,'bg'=>$bg]);
    }


    /**
     * @return string
     * 农户分布
     */
    public function actionFarmerMap()
    {
        $address = \Yii::$app->db->createCommand('select a.id,a.parentid,a.lat,a.lng,a.name,a.type,f.id as fid,f.countyid,f.townid,f.villageid,f.descripation,
              (select count(*) from '.BusinessFarmers::tableName().' f where if(a.type=4,a.id=f.countyid,1=1) and if(a.type=5,a.id=f.townid,1=1) and if(a.type=6,a.id=f.villageid,1=1)) as acount from '.BusinessAdress::tableName().' as a 
              left join '.BusinessFarmers::tableName().' as f on f.villageid=a.id where a.status='.BusinessAdress::STATUS_ACTIVE)
            ->queryAll();


        foreach($address as $key => &$row) {
            if($row['type'] == 6){
                $farmer = \Yii::$app->db->createCommand('select name,id,lng,lat,descripation,(select count(*) from '.BusinessPig::tableName().' where livery=f.id) as pignum from '.BusinessFarmers::tableName().' f where villageid=:vid')
                    ->bindValues([':vid'=>$row['id']])
                    ->queryAll();
                $row['items'] = $farmer;
            }

            $row['acount'] = '有'.$row['acount'].'家农户';
        }

        $address = Category::getTree($address,9);

        $address = \GuzzleHttp\json_encode($address);

        return $this->render('@template/screen/farmer_map.html',['address'=>$address]);
    }



    /**
     * @return string
     * 农户列表
     */
    public function actionFarmerList()
    {

        $farmers = BusinessFarmers::find()->select('name,addressdetail as address,id,phone,villageid as cunid')->where(['status'=>BusinessFarmers::STATUS_AGREE])->asArray()->all();

        $address = BusinessAdress::find()->select('id,parentid,lat,lng,name')->where('status=:status',[':status'=>BusinessAdress::STATUS_ACTIVE])->asArray()->all();
        $address = Category::getTree($address,9);

        return $this->render('@template/screen/farmer_list.html', [
                'farmers'=>\GuzzleHttp\json_encode($farmers),
                'address'=>\GuzzleHttp\json_encode($address)
            ]);
    }


    /**
     * @param $cunid
     * @return array|\yii\db\ActiveRecord[]
     * 根据村庄检索农户
     */
    public function actionSearchFarmer($cunid)
    {
        $name = \Yii::$app->request->post('name');
        if(!$name){
            $farmers = BusinessFarmers::find()->select('name,address,id,phone,,villageid as cunid')->where('villageid=:cunid and status=:status',[':cunid'=>$cunid,':status'=>BusinessFarmers::STATUS_AGREE])->asArray()->all();
        }else{
            $farmers = BusinessFarmers::find()->select('name,address,id,phone,,villageid as cunid')->where('villageid=:cunid and name like :name and status=:status',[':cunid'=>$cunid,':name'=>'%'.$name.'%',':status'=>BusinessFarmers::STATUS_AGREE])->asArray()->all();
        }

        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $farmers;

    }


    /**
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     * 农户详情
     */
    public function actionFarmerDetail($id)
    {

        $farmer = BusinessFarmers::find(['id=:id',[':id'=>$id]])->select('id,descripation,no,photo,address,name,phone')->asArray()->where('id=:id',[':id'=>$id])->one();
        $pig = BusinessPig::find()->select('id,no,status')->asArray()->where('livery=:lid',[':lid'=>$farmer['id']])->all();
        foreach ($pig as $key => &$value){
            $pig[$key]['status'] = BusinessPig::$statues[$value['status']];
            $pig[$key]['qrcode'] = Url::to(['/screen/site/qrcode','no'=>$value['no']]);
        }
        $farmer['pighousephoto'] = implode('|',Upload::checkGetUrl($farmer['photo'],true));
        $farmer['pig'] = $pig;

        \Yii::$app->response->format = Response::FORMAT_JSON;

        return $farmer;
    }


    /**
     * @param $pigid
     * @return array|\yii\db\ActiveRecord[]
     * 巡检记录详情
     */
//    public function actionRecord($id)
//    {
//        $data = BusinessInspection::find()->select('*')->where('id=:id',[':id'=>$id])->asArray()->one();
//        $data['createtime'] = date('Y-m-d',$data['createtime']);
//
//        $data['data']['体长（cm）'] = $data['length'].'cm';
//        $data['data']['体宽（cm）'] = $data['width'].'cm';
//        $data['data']['身高（cm）'] = $data['height'].'cm';
//        $data['data']['体重（kg）'] = $data['weight'].'kg';
//        $data['data']['大便'] = $data['shit'];
//        $data['data']['体温'] = $data['temperature'].'°C';
//        $data['data']['呼吸'] = $data['breath'];
//        $data['data']['毛色'] = $data['haircolor'];
//        $data['data']['活跃程度'] = $data['activelevel'];
//        $data['data']['健康状况'] = $data['healthy_desc'];
//        $data['data']['猪舍环境'] = $data['pigpen_desc'];
//        $data['data']['食料情况'] = $data['feed_desc'];
//
//        $data['pigpen_photo'] = Upload::checkGetUrl($data['pigpen_photo'],true);
//        $data['pigphoto'] = Upload::checkGetUrl($data['pigphoto'],true);
//        $data['feed_photo'] = Upload::checkGetUrl($data['feed_photo'],true);
//        $data['pigpen_photo'] = array_merge($data['pigpen_photo'],$data['pigphoto'],$data['feed_photo']);
//        $data['title'] = '于'.$data['createtime'].'巡检';
//        \Yii::$app->response->format = Response::FORMAT_JSON;
//        return $data;
//    }

    public function actionRecord($id)
    {
        $data = NewBusinessInspection::find()->select('*')->where('id=:id',[':id'=>$id])->asArray()->one();
        $data['createtime'] = date('Y-m-d',$data['createtime']);

        $detail = (new Query())->select('*')->from(NewBusinessInspectionData::tableName())->where('inspectionid=:id',[':id'=>$id])->indexBy('fieldname')->all();

//        $data['data']['体长（cm）'] = $data['length'].'cm';
//        $data['data']['体宽（cm）'] = $data['width'].'cm';
//        $data['data']['身高（cm）'] = $data['height'].'cm';
//        $data['data']['体重（kg）'] = $data['weight'].'kg';
//        $data['data']['大便'] = $data['shit'];
//        $data['data']['体温'] = $data['temperature'].'°C';
//        $data['data']['呼吸'] = $data['breath'];
//        $data['data']['毛色'] = $data['haircolor'];
//        $data['data']['活跃程度'] = $data['activelevel'];
//        $data['data']['健康状况'] = $data['healthy_desc'];
//        $data['data']['猪舍环境'] = $data['pigpen_desc'];
//        $data['data']['食料情况'] = $data['feed_desc'];

        $images = [];
        foreach ($detail as $k =>$v){
            if($v['fieldtype'] == 'image'){
                if(($photo = Upload::checkGetUrl($v['val'],true)) !== false){
                    $images = array_merge($images,$photo);
                }
                continue;
            }
            $data['data'][$v['fieldname']] = $v['val'];
        }
        $data['image'] = $images;

//        var_dump($data);exit;
//        $data['pigpen_photo'] = Upload::checkGetUrl($data['pigpen_photo'],true);
//        $data['pigphoto'] = Upload::checkGetUrl($data['pigphoto'],true);
//        $data['feed_photo'] = Upload::checkGetUrl($data['feed_photo'],true);
//        $data['pigpen_photo'] = array_merge($data['pigpen_photo'],$data['pigphoto'],$data['feed_photo']);
        $data['title'] = '于'.$data['createtime'].'巡检';
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $data;
    }


    /**
     * @param $pigid
     * @return array|bool
     * 猪肉溯源，详情
     */
//    public function actionPigDetail($pigid)
//    {
//        $pig = (new Query())->from(BusinessPig::tableName().' as p')
//            ->select('p.width,p.no,p.breath,p.shit,,p.weight,p.height,p.batch,p.gender,p.foodintake,p.activelevel,p.haircolor,liveryname,headperson,intime,lingperson,killplace,intime as lifetime,screen_photo,v.title,f.matherphoto as motherphoto,f.fatherphoto')
//            ->leftJoin(BusinessPigFile::tableName().' as f','f.id=p.fileid')
//            ->leftJoin(BusinessVariety::tableName().' as v','v.id=f.variety')
//            ->where('p.id=:id',[':id'=>$pigid])
//            ->one();
//
//        $pig['motherphoto'] = Upload::checkGetUrl($pig['motherphoto'],false,'motherphoto');
//        $pig['fatherphoto'] = Upload::checkGetUrl($pig['fatherphoto'],false,'fatherphoto');
//        $pig['photo'] = Upload::checkGetUrl($pig['screen_photo'],false,'screen_photo');
//
//
//        $pig['data']['猪种'] = $pig['title'];
//        $pig['data']['入栏时间'] = date('Y-m-d',$pig['intime']);
//        $pig['data']['巡检员'] = $pig['headperson'];
//        $pig['data']['代养农户'] = $pig['liveryname'];
//        $pig['data']['入栏时间'] = date('Y-m-d',$pig['intime']);
//        $pig['data']['批次'] = $pig['batch'];
//        $pig['data']['性别'] = $pig['gender'];
//        $pig['data']['毛色'] = $pig['haircolor'];
//        $pig['data']['饮食'] = $pig['foodintake'];
//        $pig['data']['精神状态'] = $pig['activelevel'];
//        $pig['data']['大便'] = $pig['shit'];
//        $pig['data']['呼吸'] = $pig['breath'];
//        $pig['data']['身高'] = $pig['height'];
//        $pig['data']['体重'] = $pig['weight'];
//        $pig['data']['身宽'] = $pig['width'];
//
//        $inspection = (new Query())->from(BusinessInspection::tableName())
//            ->select("id,pigpen_photo,createtime")
//            ->where('pigid=:id and status=:status',[':id'=>$pigid,':status'=>BusinessInspection::STATUS_PASSED])
//            ->all();
//
//        $end = count($inspection);
//        $inspection_photo = '';
//        foreach ($inspection as $key => $item){
//            $inspection[$key]['createtime'] = date('Y-m-d').'年第'.($key+1).'次巡检';
//            if($key = $end-1){
//                $inspection_photo = Upload::checkGetUrl($item['pigpen_photo']);
//            }
//        }
//        $pig['inspection'] = $inspection;
//        $pig['inspection_photo'] = $inspection_photo;
//
//        \Yii::$app->response->format = Response::FORMAT_JSON;
//        return $pig;
//    }


    public function actionPigDetail($pigid)
    {
        $pig = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('p.width,p.no,p.breath,p.shit,,p.weight,p.height,p.batch,p.gender,p.foodintake,p.activelevel,p.haircolor,liveryname,headperson,intime,lingperson,killplace,intime as lifetime,screen_photo,v.title,f.matherphoto as motherphoto,f.fatherphoto')
            ->leftJoin(BusinessPigFile::tableName().' as f','f.id=p.fileid')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=f.variety')
            ->where('p.id=:id',[':id'=>$pigid])
            ->one();


        //仔猪信息
        $pig['motherphoto'] = Upload::checkGetUrl($pig['motherphoto'],false,'motherphoto');
        $pig['fatherphoto'] = Upload::checkGetUrl($pig['fatherphoto'],false,'fatherphoto');
        $pig['photo'] = Upload::checkGetUrl($pig['screen_photo'],false,'screen_photo');
        $pig['data']['猪种'] = $pig['title'];
        $pig['data']['入栏时间'] = date('Y-m-d',$pig['intime']);
        $pig['data']['巡检员'] = $pig['headperson'];
        $pig['data']['代养农户'] = $pig['liveryname'];
        $pig['data']['批次'] = $pig['batch'];

        if(!empty($pig['gender'])){
            $pig['data']['性别'] = $pig['gender'];
        }

        //最后一次巡检信息
        $detail = (new Query())->select('*')
            ->from(NewBusinessInspectionData::tableName().' as idata')
            ->leftJoin(NewBusinessInspection::tableName().' ins','idata.inspectionid=ins.id')
            ->orderBy('ins.createtime desc')
            ->where('ins.pigid=:id ',[':id'=>$pigid])
            ->indexBy('fieldname')
            ->all();

        foreach ($detail as $k =>$v){
            if($v['fieldtype'] == 'input' || $v['fieldtype'] == 'select'){
                if(mb_strlen($v['val']) < 6){
                    $pig['data'][$v['fieldname']] = $v['val'];
                }
            }
        }

        //仔猪初始化信息
//        $pig['data']['毛色'] = $pig['haircolor'];
//        $pig['data']['饮食'] = $pig['foodintake'];
//        $pig['data']['精神状态'] = $pig['activelevel'];
//        $pig['data']['大便'] = $pig['shit'];
//        $pig['data']['呼吸'] = $pig['breath'];
//        $pig['data']['身高'] = $pig['height'];
//        $pig['data']['体重'] = $pig['weight'];
//        $pig['data']['身宽'] = $pig['width'];


        $inspection = (new Query())->from(NewBusinessInspection::tableName())
            ->select("id,createtime")
            ->where('pigid=:id and status=:status',[':id'=>$pigid,':status'=>NewBusinessInspection::STATUS_PASSED])
            ->all();

        foreach ($inspection as $key => $item){
            $inspection[$key]['createtime'] = date('Y-m-d').'年第'.($key+1).'次巡检';
        }
        $pig['inspection'] = $inspection;
        $pig['inspection_photo'] = '';


        \Yii::$app->response->format = Response::FORMAT_JSON;
        return $pig;
    }


    /**
     * @return string
     * 企业简介
     */
    public function actionIntroduction()
    {

        $article = ArticlesiteArticle::findOne(['type'=>ArticlesiteArticle::ARTICLE_TYPE_ABOUT]);
        return $this->render('@template/screen/introduction.html',['article'=>$article]);
    }


    /**
     * @return string
     * 动态
     */
    public function actionNews()
    {
        $list = (new Query())->select('c.id as cateid,a.id,c.name,a.title as text,a.thumb as img,a.descripation,a.createtime as time')
            ->from(ArticlesiteCategory::tableName().' as c')
            ->leftJoin(ArticlesiteArticle::tableName().' as a','a.cateid=c.id')
            ->where('a.status=:status and c.usefor=:usefor and type=:type',[':status'=>ArticlesiteArticle::ARTICLE_SHOW,':usefor'=>ArticlesiteArticle::USEFOR_SCREEN,':type'=>ArticlesiteArticle::ARTICLE_TYPE_NORMAL])
            ->all();


        foreach($list as $key => $row){
            $row['url'] = Url::to(['/screen/site/news-detail','id'=>$row['id']]);
            $row['img'] = Upload::UploadUrl($row['img']);
            $row['time'] = date('Y-m-d H:i:s',$row['time']);
            $article[$row['name']][] = $row;
        }

        $article = \GuzzleHttp\json_encode($article);

//        var_dump($article);exit;
        $about = ArticlesiteArticle::find()->where(['type'=>ArticlesiteArticle::ARTICLE_TYPE_ABOUT])->asArray()->one();
        return $this->render('@template/screen/news.html',['article'=>$article,'about'=>$about['content']]);
    }


    /**
     * @return string
     * 文章详情
     */
    public function actionNewsDetail()
    {
        $id = \Yii::$app->request->get('id');
        $article = ArticlesiteArticle::findOne(['id'=>$id]);
        return $this->render('@template/screen/newsdetail.html',['article'=>$article]);
    }


    /**
     * @param $no
     * @return mixed
     * 二维码
     */
    public function actionQrcode($no)
    {
        $response = \Yii::$app->response;
        $response->headers->set('Content-Type', 'image/png');
        $response->format = Response::FORMAT_RAW;
//        $pig = (new Query())->select('id')->from(BusinessPig::tableName())->where('no=:no',[':no'=>$pigno])->one();
        return QrCode::png(\Yii::$app->request->hostInfo.'/shop/site/from?pigid='.$no);
    }








}
